package com.systop.ltbook.book.webapp;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.util.ArrayUtils;
import com.systop.cms.utils.PageUtil;
import com.systop.common.modules.security.user.LoginUserService;
import com.systop.core.dao.support.Page;
import com.systop.core.webapp.struts2.action.ExtJsCrudAction;
import com.systop.core.webapp.upload.UpLoadUtil;
import com.systop.ltbook.BookConstants;
import com.systop.ltbook.book.model.Book;
import com.systop.ltbook.book.press.model.Press;
import com.systop.ltbook.book.press.service.PressManager;
import com.systop.ltbook.book.service.BookManager;
import com.systop.ltbook.book.subject.model.Subject;
import com.systop.ltbook.book.subject.service.SubjectManager;
import com.systop.ltbook.mainpage.MainPageAction;

/**
 * <code>Book</code>对象的struts2 action。
 * 
 * @author DU
 */
@SuppressWarnings({ "serial", "unchecked" })
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class BookAction extends ExtJsCrudAction<Book, BookManager> {

	/**
	 * 图书ID
	 */
	private Integer bookId;

	/**
	 * 图书封面
	 */
	private File photo;

	/**
	 * 图书封面存储名称
	 */
	private String photoFileName;

	/**
	 * json返回结果
	 */
	private Map<String, String> delResult;

	/**
	 * 图书类型列表
	 */
	protected String[] bkTypes;

	/**
	 * 登陆用户信息管理
	 */
	@Autowired
	private LoginUserService loginUserService;

	@Autowired
	private SubjectManager subjectManager;

	@Autowired
	private PressManager pressManager;

	/**
	 * 图书管理查询列表
	 */
	@Override
	public String index() {
		StringBuffer hql = new StringBuffer("from Book bk where 1=1 ");
		List args = new ArrayList();

		// 当前登录用户所在部门
		/*
		 * Dept county = loginUserService.getLoginUserDept(getRequest()); if
		 * (county != null) {
		 * 
		 * }
		 */

		// 按书名查询
		if (StringUtils.isNotBlank(getModel().getName())) {
			hql.append(" and bk.name like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(getModel().getName()));
		}
		// 按图书ISBN编号查询
		if (StringUtils.isNotBlank(getModel().getIsbn())) {
			hql.append(" and bk.isbn like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(getModel().getIsbn()));
		}
		// 按图书类型查询
		if (ArrayUtils.isNotEmpty(bkTypes)) {
			String bkType = convertArrayToString(bkTypes, ",");
			if (bkTypes.length == 3) {
				hql.append(" and bk.bkType = ?");
				args.add(bkType);
			} else if (bkTypes.length == 2) {
				if ("1,3".equals(bkType)) {
					hql.append(" and (bk.bkType = ? or bk.bkType = ?)");
					args.add("1,3");
					args.add("1,2,3");
				} else {
					hql.append(" and bk.bkType like ?");
					args.add(MatchMode.ANYWHERE.toMatchString(bkType));
				}
			} else {
				hql.append(" and bk.bkType like ?");
				args.add(MatchMode.ANYWHERE.toMatchString(bkType));
			}
		}
		// 按年级查询
		if (StringUtils.isNotBlank(getModel().getGrade())) {
			// 小学、初中、高中、考试
			if (getModel().getGrade().equals(BookConstants.GRADE_PRIMARY)
					|| getModel().getGrade().equals(BookConstants.GRADE_JUNIOR)
					|| getModel().getGrade().equals(BookConstants.GRADE_SENIOR)
					|| getModel().getGrade().equals(BookConstants.GRADE_EXAM)) {
				hql.append(" and bk.grade like ?");
				args.add(MatchMode.ANYWHERE
						.toMatchString(getModel().getGrade()));
			} else {
				hql.append(" and bk.grade = ?");
				args.add(getModel().getGrade());
			}
		}
		// 按学科查询
		if (getModel().getSubject() != null
				&& getModel().getSubject().getId() != null) {
			hql.append(" and bk.subject.id = ?");
			args.add(getModel().getSubject().getId());
		}
		// 按图书ID排序
		hql.append(" order by bk.id desc");
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);
		return INDEX;
	}

	/**
	 * 保存图书信息
	 */
	@Override
	public String save() {
		try {
			if (photo != null) {
				String fileRelativePath = null;
				fileRelativePath = UpLoadUtil.doUpload(photo, photoFileName,
						BookConstants.BOOK_PHOTOS_FOLDER, getServletContext(),
						true);
				logger.debug("photo path:{}", fileRelativePath);
				getModel().setCoverPhoto(fileRelativePath);
			}
			/*
			 * Dept dept = loginUserService.getLoginUserDept(getRequest());
			 * logger.debug("图书所属部门：{}", dept.getName()); //图书所属部门
			 * getModel().setDept(dept);
			 */
			// 学科
			if (getModel().getSubject() != null) {
				Subject subject = getManager().getDao().get(Subject.class,
						getModel().getSubject().getId());
				getModel().setSubject(subject);
			}
			// 出版社
			if (getModel().getPress() != null) {
				Press press = getManager().getDao().get(Press.class,
						getModel().getPress().getId());
				getModel().setPress(press);
			}
			// 类型
			if (ArrayUtils.isNotEmpty(bkTypes)) {
				String types = convertArrayToString(bkTypes, ",");
				logger.debug("您选择的图书类型是：{}", types);
				getModel().setBkType(types);
			} else {
				getModel().setBkType(null);
			}
			getModel().setUpdateTime(new Date());
			getManager().getDao().clear();
			getManager().save(getModel());
			return SUCCESS;
		} catch (Exception e) {
			addActionError(e.getMessage());
			return INPUT;
		}
	}

	/**
	 * 删除图书信息
	 */
	@Override
	public String remove() {
		Book book = getManager().get(getModel().getId());
		// 检查是否与订单关联
		/*
		 * if (book.getOrderForms.size() != 0) {
		 * addActionError("该图书涉及客户订单，不能删除！"); return INDEX; }
		 */
		if (book.getFavorites().size() != 0) {
			addActionError("该图书涉及客户收藏，不能删除！");
			return INDEX;
		}
		MainPageAction.resetNewBooks();
		MainPageAction.resetHotBooks();
		MainPageAction.resetCheepBooks();
		// 如果存在照片，则连照片一起删除
		String Path = getModel().getCoverPhoto();
		if (StringUtils.isNotBlank(Path)) {
			getManager().remove(book, getRealPath(Path));
			return SUCCESS;
		}

		return super.remove();
	}

	/**
	 * 删除图书封面照片
	 */
	public String deletePhoto() {
		logger.debug("要删除的图书ID:" + bookId);
		delResult = Collections.synchronizedMap(new HashMap<String, String>());
		// 对于编辑图书信息的情况，处理删除原照片的请求
		if (bookId != null) {
			Book book = getManager().get(bookId);
			String relativePath = book.getCoverPhoto();
			if (StringUtils.isNotEmpty(relativePath)) {
				File file = new File(getServletContext().getRealPath(
						relativePath));
				if (file.exists()) {
					file.delete();
				}
			}
			// 删除数据库中图书封面照片的路径
			book.setCoverPhoto(null);
			getManager().save(book);
			delResult.put("result", "success");
		} else {
			delResult.put("result", "error");
		}
		return "jsonRst";
	}

	/**
	 * 取得所有的学科列表
	 */
	public List<Map> getSubjectList() {
		List list = Collections.EMPTY_LIST;
		list = subjectManager.getAllSubjects();
		return list;
	}

	/**
	 * 取得所有的出版社列表
	 */
	public List<Map> getPressList() {
		List list = Collections.EMPTY_LIST;
		list = pressManager.getAllpresses();
		return list;
	}

	/**
	 * 图书类型
	 */
	public Map getBookTypeMap() {
		return BookConstants.BOOK_TYPE_MAP;
	}

	/**
	 * 取得年级_下拉框
	 */
	public Map getGradeMap() {
		return BookConstants.GRADE_MAP;
	}
	
	/** 包装描述 */
	public Map getPackdescnMap(){
		return BookConstants.PACKDESCN_MAP;
	}
	
	/** 纸张描述 */
	public Map getPaperdescMap(){
		return BookConstants.PAPERDESC_MAP;
	}
	
	/** 开本类型 */
	public Map getBooksizeMap(){
		return BookConstants.BOOKSIZE_MAP;
	}

	public Map getGradeNameMap() {
		return BookConstants.GRADE_NAME_MAP;
	}

	/**
	 * 将字符串数组按指定分隔符转换成字符串
	 * 
	 * @param strArray
	 *            字符串数组
	 * @param separator
	 *            分隔符
	 */
	private String convertArrayToString(String[] strArray, String separator) {
		StringBuffer strbuf = new StringBuffer();
		for (int i = 0; i < strArray.length; i++) {
			strbuf.append(separator).append(strArray[i]);
		}
		return strbuf.deleteCharAt(0).toString();
	}

	public File getPhoto() {
		return photo;
	}

	public void setPhoto(File photo) {
		this.photo = photo;
	}

	public String getPhotoFileName() {
		return photoFileName;
	}

	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}

	public Integer getBookId() {
		return bookId;
	}

	public void setBookId(Integer bookId) {
		this.bookId = bookId;
	}

	public Map<String, String> getDelResult() {
		return delResult;
	}

	public void setDelResult(Map<String, String> delResult) {
		this.delResult = delResult;
	}

	public String[] getBkTypes() {
		return bkTypes;
	}

	public void setBkTypes(String[] bkTypes) {
		this.bkTypes = bkTypes;
	}
	
	@Deprecated
	public String reSaveBooks(){
		String hql = "from Book b";
		List<Book> books = getManager().query(hql);
		for(Book b :books){
			b.setPackDescn(StringUtils.trim(b.getPackDescn()));
			b.setPaperDesc(StringUtils.trim(b.getPaperDesc()));
			b.setBookSize(StringUtils.trim(b.getBookSize()));
			
			if (b.getPackDescn() != null){
				if ("平装".equals(b.getPackDescn())){
					b.setPackDescn(BookConstants.PACKDESCN_PZ);
				}else if ("精装".equals(b.getPackDescn())){
					b.setPackDescn(BookConstants.PACKDESCN_JZ);
				}else if ("袋装".equals(b.getPackDescn())){
					b.setPackDescn(BookConstants.PACKDESCN_DZ);
				}else if ("盒装".equals(b.getPackDescn())){
					b.setPackDescn(BookConstants.PACKDESCN_HZ);
				}
			}
			//==============
			if (StringUtils.isNotBlank(b.getPaperDesc())){
				if (b.getPaperDesc().startsWith("胶")){
					b.setPaperDesc(BookConstants.PAPERDESC_JB);
				}else if (b.getPaperDesc().startsWith("铜")){
					b.setPaperDesc(BookConstants.PAPERDESC_TB);
				}
			}
			if (b.getBookSize() != null){
				if(b.getBookSize().startsWith("8")){
					b.setBookSize(BookConstants.BOOKSIZE_8);
				}else if(b.getBookSize().startsWith("大16")){
					b.setBookSize(BookConstants.BOOKSIZE_B16);
				}else if(b.getBookSize().startsWith("16")){
					b.setBookSize(BookConstants.BOOKSIZE_16);
				}else if(b.getBookSize().startsWith("24")){
					b.setBookSize(BookConstants.BOOKSIZE_24);
				}else if(b.getBookSize().startsWith("大32")){
					b.setBookSize(BookConstants.BOOKSIZE_B32);
				}else if(b.getBookSize().startsWith("32")){
					b.setBookSize(BookConstants.BOOKSIZE_32);
				}else if(b.getBookSize().startsWith("64")){
					b.setBookSize(BookConstants.BOOKSIZE_64);
				}
			}
			System.out.println(b.getId());
			getManager().save(b);
		}
		return SUCCESS;
	}
	
	@Deprecated
	public String reSetPress(){
		String hql = "select p.id from Press p group by p.name";
		List<Integer> pressIds = getManager().getDao().query(hql);
		for(Integer id : pressIds){
			Press press = getManager().getDao().get(Press.class, id);
			hql = "from Book b where b.press.name = ?";
			List<Book> books = getManager().query(hql, press.getName());
			System.out.print(press.getName() + ":更新...");
			for(Book b : books){
				if (b.getPress().getId() != press.getId()){
					b.setPress(press);
					getManager().save(b);
					System.out.print(".");
				}
			}
			System.out.println(press.getName() + ":更新完毕");
		}
		return SUCCESS;
	}
	
	public String badImg(){
		String realPath = getServletContext().getRealPath(BookConstants.BOOK_PHOTOS_FOLDER + "bad/");
		File badImgFolder = new File(realPath);
		List<Book> books = null;
		if (badImgFolder.exists()){
			File[] imgs = badImgFolder.listFiles();
			String hql = "from Book b where b.coverPhoto like ?";
			books = new ArrayList<Book>();
			for(File img : imgs){
				String fileName = img.getName();
				Book b = getManager().findObject(hql, "%" + fileName);
				if (b != null){
					books.add(b);
				}
			}
		}
		getRequest().setAttribute("books", books);
		return "badImgBooks";
	}
}
